import * as fs from 'fs';
import * as path from 'path';
import axios, { CancelTokenSource } from 'axios';
import * as os from 'os';
import { logger } from './logger';
import * as vscode from 'vscode';
export async function downloadImage(url: string, fileName?: string): Promise<void> {
  // Get home directory
  const homeDir = os.homedir();
  logger.info(`homeDir is ${homeDir}`);
  const targetDir = path.join(homeDir, '.image');
  
  // Create .a directory if it doesn't exist
  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir);
    logger.info(`Created directory: ${targetDir}`);
  }
  
  // Set default filename if not provided
  const defaultFileName = fileName || path.basename(url);
  const filePath = path.join(targetDir, defaultFileName);
  

  const cancellationTokenSource = new vscode.CancellationTokenSource();
  const axiosCancelTokenSource = axios.CancelToken.source();
    
  vscode.window.withProgress({
      location: vscode.ProgressLocation.Notification,
      title: `Begin to Download Image...`,
      cancellable: true
  },
  async (progress, token) => {
    // Handle cancellation
    token.onCancellationRequested(() => {
      logger.info('User cancelled the download');
      axiosCancelTokenSource.cancel('User cancelled the download');
      cancellationTokenSource.cancel();
      vscode.window.showInformationMessage('Image download cancelled');
    });

    try {
        // Record start time
        const startTime = Date.now();
        
        // Download file with cancellation support
        const response = await axios({
          method: 'GET',
          url: url,
          responseType: 'stream',
          cancelToken: axiosCancelTokenSource.token
        });
        
        // Save to file
        const writer = fs.createWriteStream(filePath);
        response.data.pipe(writer);
        
        return new Promise((resolve, reject) => {
          writer.on('finish', () => {
            // Calculate download time
            const endTime = Date.now();
            const timeInSeconds = ((endTime - startTime) / 1000).toFixed(2);
            vscode.window.showInformationMessage(`Download completed in ${timeInSeconds} seconds`);
            resolve(1);
          });
          writer.on('error', (err) => {
            // Close the writer to prevent resource leaks
            writer.close();
            if (token.isCancellationRequested) {
              // Delete the partial file if download was cancelled
              if (fs.existsSync(filePath)) {
                fs.unlinkSync(filePath);
                logger.info(`Removed partial download: ${filePath}`);
              }
              resolve(0); // Resolve without error on cancellation
            } else {
              reject(err);
            }
          });
        });
      } catch (error) {
        if (axios.isCancel(error)) {
          // Handle the cancellation error gracefully
          logger.info(`Download cancelled: ${error.message}`);
          // Delete the partial file if it exists
          if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
            logger.info(`Removed partial download: ${filePath}`);
          }
          return Promise.resolve(); // Resolve without error
        }
        logger.error('Download failed:'+ error);
        vscode.window.showErrorMessage(`Download failed: ${(error as Error).message || 'Unknown error'}`);
        throw error;
      }
  });
}